<template>
  <div class="pending-buy-monitor">
    <el-card class="monitor-card">
      <template #header>
        <div class="card-header">
          <span>待买入池股价监控</span>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="refreshData" :loading="loading">
              {{ loading ? '刷新中...' : '刷新' }}
            </el-button>
            <el-select 
              v-model="refreshIntervalMinutes" 
              size="small" 
              style="width: 80px; margin-left: 8px;"
              @change="updateRefreshInterval"
            >
              <el-option :value="0" label="关闭" />
              <el-option :value="1" label="1分钟" />
              <el-option :value="5" label="5分钟" />
              <el-option :value="15" label="15分钟" />
            </el-select>
          </div>
        </div>
      </template>
      
      <div class="monitor-content">
        <el-empty 
          v-if="total === 0 && !loading" 
          description="暂无待买入股票"
          :image-size="80"
        />
        
        <div v-else-if="loading" class="loading-container">
          <el-loading :loading="loading" text="加载中..."></el-loading>
        </div>
        
        <div v-else class="stock-grid">
          <div 
            v-for="item in monitoredStocks" 
            :key="item.id"
            class="stock-mini-card"
            :class="getCardClass(item)"
            @click="handleCardClick(item)"
          >
            <div class="stock-header">
              <span class="stock-name-mini">{{ item.stockName }}</span>
              <span class="stock-code-mini">{{ item.stockCode }}</span>
            </div>
            
            <div class="price-display">
              <div class="current-price-mini">
                {{ item.currentPrice > 0 ? `¥${item.currentPrice}` : '--' }}
              </div>
              <div class="target-price-mini">
                目标: ¥{{ item.buyPrice }}
              </div>
            </div>
            <div class="waiting-points" v-if="item.currentPrice > 0">
                <span class="points-label">等待点数:</span>
                <span :class="{'points-positive': (item.currentPrice - item.buyPrice) * 1000 >= 0, 'points-negative': (item.currentPrice - item.buyPrice) * 1000 < 0}">
                    {{ ((item.currentPrice - item.buyPrice) * 1000 + 1).toFixed(0) }}
                </span>
                </div>
                <div class="waiting-points" v-else>
                <span class="points-label">等待点数:</span>
                <span>--</span>
            </div>
            <div class="status-indicator">
              <el-tag 
                v-if="item.currentPrice > 0"
                :type="item.currentPrice < item.buyPrice ? 'success' : 'info'"
                size="small"
                effect="dark"
                class="status-tag"
              >
                {{ item.currentPrice < item.buyPrice ? '可买' : '等待' }}
              </el-tag>
              <el-tag 
                v-else
                type="danger"
                size="small"
                effect="dark"
                class="status-tag"
              >
                异常
              </el-tag>
            </div>
            
            <div class="mini-actions">
              <el-tooltip 
                v-if="item.currentPrice === 0"
                content="重试获取价格"
                placement="top"
              >
                <el-button 
                  type="text" 
                  size="small" 
                  icon="el-icon-refresh"
                  @click.stop="retryGetPrice(item)"
                  :loading="retryingStocks.has(item.stockCode)"
                  class="mini-btn"
                />
              </el-tooltip>
              <el-tooltip 
                v-else
                content="立即买入"
                placement="top"
              >
                <el-button 
                  type="text" 
                  size="small" 
                  icon="el-icon-shopping-cart-2"
                  @click.stop="goToBuy(item)"
                  :disabled="item.currentPrice >= item.buyPrice"
                  class="mini-btn"
                />
              </el-tooltip>
            </div>
          </div>
        </div>
        
        <!-- 分页控件 -->
        <el-pagination
          v-if="total > 0"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[12, 24, 48, 96]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 16px; text-align: center;"
        />
      </div>
      
      <div class="monitor-footer">
        <div class="summary-mini">
          共{{ total }}只，{{ alertCount }}只可买，{{ errorCount }}只异常
        </div>
        <div class="last-update-mini">
          {{ lastUpdateTime }}
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { pageStockPendingBuyPool } from '@/api/stockPendingBuyPool'
import { getClosePrice } from '@/api/realtime'

export default {
  name: 'StockPendingBuyMonitor',
  data() {
    return {
      pendingBuyList: [],
      monitoredStocks: [],
      loading: false,
      refreshInterval: null,
      refreshIntervalMinutes: 0,
      retryingStocks: new Set(),
      lastUpdateTime: '未更新',
      // 分页相关数据
      currentPage: 1,
      pageSize: 12,
      total: 0,
      allStocks: [] // 存储所有股票数据
    }
  },
  computed: {
    alertCount() {
      return this.monitoredStocks.filter(
        item => item.currentPrice < item.buyPrice && item.currentPrice > 0
      ).length
    },
    errorCount() {
      return this.monitoredStocks.filter(item => item.currentPrice === 0).length
    }
  },
  mounted() {
    this.loadPendingBuyData()
    this.startRefreshInterval()
  },
  beforeUnmount() {
    this.clearRefreshInterval()
  },
  methods: {
    getCardClass(item) {
      return {
        'buy-ready': item.currentPrice < item.buyPrice && item.currentPrice > 0,
        'price-error': item.currentPrice === 0,
        'waiting': item.currentPrice >= item.buyPrice && item.currentPrice > 0
      }
    },
    
    handleCardClick(item) {
      if (item.currentPrice > 0 && item.currentPrice < item.buyPrice) {
        this.goToBuy(item)
      }
    },
    
    // 分页相关方法
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.updateDisplayedStocks()
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
      this.updateDisplayedStocks()
    },
    
    updateDisplayedStocks() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.pendingBuyList = this.allStocks.slice(start, end)
      this.refreshCurrentPrices()
    },
    
    startRefreshInterval() {
      this.clearRefreshInterval()
      if (this.refreshIntervalMinutes > 0) {
        this.refreshInterval = setInterval(() => {
          this.loadPendingBuyData()
        }, this.refreshIntervalMinutes * 60 * 1000)
      }
    },
    
    clearRefreshInterval() {
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval)
        this.refreshInterval = null
      }
    },
    
    updateRefreshInterval() {
      this.startRefreshInterval()
      this.$message.success(
        this.refreshIntervalMinutes > 0 
          ? `已设置${this.refreshIntervalMinutes}分钟自动刷新` 
          : '已关闭自动刷新'
      )
    },
    
    async loadPendingBuyData() {
      this.loading = true
      try {
        const response = await pageStockPendingBuyPool({ 
          pageNum: 1, 
          pageSize: 1000 // 获取所有数据用于前端分页
        })
        if (response.code === 200) {
          this.allStocks = response.data || []
          this.total = this.allStocks.length
          this.updateDisplayedStocks()
        }
      } catch (error) {
        this.$message.error('获取待买入池数据失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },
    
    async refreshCurrentPrices() {
      if (this.pendingBuyList.length === 0) return
      
      this.loading = true
      const stockCodes = this.pendingBuyList.map(item => item.stockCode)
      
      try {
        const results = await this.batchGetPrices(stockCodes)
        
        this.monitoredStocks = this.pendingBuyList.map(item => ({
          ...item,
          currentPrice: results[item.stockCode] || 0
        }))
        
        this.lastUpdateTime = new Date().toLocaleTimeString()
        this.checkPriceAlerts()
        
      } catch (error) {
        console.error('批量获取价格失败:', error)
        this.monitoredStocks = this.pendingBuyList.map(item => ({
          ...item,
          currentPrice: 0
        }))
      } finally {
        this.loading = false
      }
    },
    
    async batchGetPrices(stockCodes, batchSize = 4) {
      const results = {}
      
      for (let i = 0; i < stockCodes.length; i += batchSize) {
        const batch = stockCodes.slice(i, i + batchSize)
        const promises = batch.map(async code => {
          try {
            const price = await this.getPriceWithTimeout(code, 600000)
            results[code] = price
          } catch (error) {
            results[code] = 0
          }
        })
        
        await Promise.allSettled(promises)
        
        if (i + batchSize < stockCodes.length) {
          await new Promise(resolve => setTimeout(resolve, 200))
        }
      }
      
      return results
    },
    
    async getPriceWithTimeout(stockCode, timeout = 30000) {  // 改为30秒
      try {
        const price = await Promise.race([
          getClosePrice(stockCode),
          new Promise((_, reject) => 
            setTimeout(() => reject(new Error('请求超时')), timeout)
          )
        ])
        return parseFloat(price) || 0
      } catch (error) {
        console.error(`获取${stockCode}价格失败:`, error.message)
        return 0
      }
    },
    
    async retryGetPrice(item) {
      if (this.retryingStocks.has(item.stockCode)) return
      
      this.retryingStocks.add(item.stockCode)
      try {
        const price = await this.getPriceWithTimeout(item.stockCode, 45000)  // 改为45秒
        
        const index = this.monitoredStocks.findIndex(s => s.id === item.id)
        if (index !== -1) {
          this.monitoredStocks[index].currentPrice = parseFloat(price) || 0
        }
        
        if (price > 0) {
          this.$message.success(`${item.stockName}价格已更新`)
          this.checkPriceAlerts()
        }
      } finally {
        this.retryingStocks.delete(item.stockCode)
      }
    },
    
    async refreshData() {
      await this.loadPendingBuyData()
      this.$message.success('数据已刷新')
    },
    
    checkPriceAlerts() {
      const alertStocks = this.monitoredStocks.filter(
        item => item.currentPrice < item.buyPrice && item.currentPrice > 0
      )
      
      if (alertStocks.length > 0) {
        this.$notify({
          title: '买入提醒',
          message: `${alertStocks.length}只股票价格已达标`,
          type: 'success',
          duration: 3000,
          position: 'top-right'
        })
      }
    },
    
    goToBuy(item) {
      this.$router.push({
        name: 'StockTrading',
        query: {
          stockCode: item.stockCode,
          stockName: item.stockName,
          targetPrice: item.buyPrice
        }
      })
    }
  }
}
</script>

<style scoped>
.pending-buy-monitor {
  margin: 10px 0;
}

.monitor-card {
  border-radius: 8px;
  box-shadow: 0 1px 8px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 14px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 6px;
}

.stock-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 8px;
  padding: 8px 0;
}

.stock-mini-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
}

.stock-mini-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}

.stock-mini-card.buy-ready {
  border-color: #67c23a;
  background-color: #f0f9ff;
}

.stock-mini-card.price-error {
  border-color: #f56c6c;
  background-color: #fef0f0;
}

.stock-mini-card.waiting {
  border-color: #909399;
  background-color: #f5f7fa;
}

.stock-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.stock-name-mini {
  font-size: 13px;
  font-weight: bold;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.stock-code-mini {
  font-size: 11px;
  color: #909399;
}

.price-display {
  text-align: center;
  margin-bottom: 4px;
}

.current-price-mini {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  line-height: 1.2;
}

.target-price-mini {
  font-size: 11px;
  color: #909399;
  margin-top: 2px;
}

.waiting-points {
  text-align: center;
  margin-bottom: 4px;
  font-size: 11px;
}

.points-label {
  color: #909399;
}

.points-positive {
  color: #67c23a;
  font-weight: bold;
}

.points-negative {
  color: #f56c6c;
  font-weight: bold;
}

.status-indicator {
  text-align: center;
}

.status-tag {
  padding: 2px 6px;
  font-size: 10px;
}

.mini-actions {
  position: absolute;
  top: 4px;
  right: 4px;
}

.mini-btn {
  padding: 2px;
  font-size: 12px;
}

.monitor-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 8px;
  border-top: 1px solid #e4e7ed;
  font-size: 12px;
  color: #606266;
}

.summary-mini {
  font-weight: bold;
}

.last-update-mini {
  font-size: 11px;
  color: #909399;
}

@media (max-width: 768px) {
  .stock-grid {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 6px;
  }
  
  .stock-mini-card {
    padding: 6px;
  }
}
</style>